package com.sky.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import com.sky.constant.StatusConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;

    //根据开始和结束日期活动日期列表(单独抽取出来,以备后面通用)
    private  List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        //1 计算时间范围
        List<LocalDate> dateList = new ArrayList<>();
        //循环指针
        LocalDate dateIndex = begin;
        while (!dateIndex.isAfter(end)) {
            dateList.add(dateIndex);//
            dateIndex = dateIndex.plusDays(1);//指针后移1天
        }
        log.info("得到的日期集合:{}", dateList);
        return dateList;
    }


    // 根据订单状态和指定日期范围内 的 营业额统计
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
      /*  //1. 根据传入的begin和end,构建一个日期集合
        List<LocalDate> dateList = getDateList(begin, end);

        //2. 声明返回变量
        List turnoverList = new ArrayList();//营业额集合

        //3. 凑数据
        for (LocalDate date : dateList) {
            double amount = reportMapper.sumOrderAmountByStatusAndDate(5, date);
            turnoverList.add(amount);
        }
*/
        //1计算时间范围(集合)
        List<LocalDate> dateList = getDateList(begin, end);
        //2 准备数据变量
        List<Double> turnoverList = new ArrayList<>();
        //3 遍历时间集合,获取每个日期的营业额(查询sql 凑数据)
        dateList.stream().forEach(date -> {
            Double turnover = reportMapper.sumOrderAmountByStatusAndDate(5, date);
            turnoverList.add(turnover);
        });
        //4 准备VO并返回数据
        return TurnoverReportVO.builder()//
                .dateList(CollUtil.join(dateList, ","))//2025-2-16 ,2025-2-17,2025-2-18
                .turnoverList(CollUtil.join(turnoverList, ","))//123.00,456.00,789.00
                .build();

    }


    // 在指定日期范围查询  统计用户数量
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1 计算时间范围(集合)
        List<LocalDate> dateList = getDateList(begin, end);
        //2 准备数据变量
        List newUserList = new ArrayList(); // 每天新增用户数
        List totalUserList = new ArrayList(); // 每天累计新增用户数

        Integer totalUser = 0;// 累计用户数(计数器)
        for (LocalDate date : dateList) {
            // 获取每天新增用户数
            Integer newUser = reportMapper.countUserByDate(date);
            newUserList.add(newUser);
            // 累计用户数
            totalUser += newUser;
            totalUserList.add(totalUser);

        }
        //4. 组装返回结果
        return UserReportVO.builder()//
                .dateList(CollUtil.join(dateList, ","))//2025-2-16 ,2025-2-17,2025-2-18
                .newUserList(CollUtil.join(newUserList, ","))//123.00,456.00,789.00
                .totalUserList(CollUtil.join(totalUserList, ","))//123.00,456.00,789.00
                .build();
    }


    // 根据订单状态和指定的日期  统计订单数量
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1 计算时间范围(集合)
        List<LocalDate> dateList = getDateList(begin, end);
        //2 准备数据变量
        List<Integer> orderCountList = new ArrayList();// 每天的订单总数
        List<Integer> validOrderCountList = new ArrayList();// 每天有效订单总数
        Integer totalOrderCount = 0;//订单总数
        Integer totalValidOrderCount = 0;//有效订单总数
        Double orderCompletionRate = 0.0;//订单完成率

        //3 查询SQL 凑数据
        for (LocalDate date : dateList) {
            //3-1 查询每日订单数
            Integer orderCount = reportMapper.countOrderByStatusAndDate(null, date);
            orderCountList.add(orderCount);
            //3-2 累加订单总数
            totalOrderCount += orderCount;
            //3-3 查询每日有效订单数
            Integer validOrderCount = reportMapper.countOrderByStatusAndDate(4, date);
            validOrderCountList.add(validOrderCount);
            //3-4 累加有效订单总数
            totalValidOrderCount += validOrderCount;

            }
        //4 计算订单完成率
        if (totalOrderCount > 0 && totalValidOrderCount > 0) {
            orderCompletionRate = totalValidOrderCount * 1.0 / totalOrderCount;
            // 四舍五入 保留4位小数
            orderCompletionRate = NumberUtil.round(orderCompletionRate, 4).doubleValue();//保留小数点oder
        }
        //5 组装返回结果
        return OrderReportVO.builder()
                .dateList(CollectionUtil.join(dateList,","))
                .orderCountList(CollectionUtil.join(orderCountList,","))
                .validOrderCountList(CollectionUtil.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalValidOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    // 查询销量排名前10
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1. 声明返回变量
        List<String> nameList = new ArrayList();
        List<Integer> numberList = new ArrayList();

        //2. 凑数据
        List<GoodsSalesDTO> list = reportMapper.top10(begin, end);
        if (CollectionUtil.isNotEmpty(list)) {
            for (GoodsSalesDTO dto : list) {
                nameList.add(dto.getName());
                numberList.add(dto.getNumber());
            }
        }

        //3. 返回结果
        return SalesTop10ReportVO.builder()
                .nameList(CollectionUtil.join(nameList,","))
                .numberList(CollectionUtil.join(numberList,","))
                .build();
    }



    // 查询工作台  今日数据
    @Override
    public BusinessDataVO getBusinessData(LocalDate today) {
        //1. 获取今日日期
        //LocalDate today = LocalDate.now();
        //2 查询SQL 凑数据
        Integer newUsers = reportMapper.countUserByDate(today);//今日新增用户数
        Double turnover = reportMapper.sumOrderAmountByStatusAndDate(5,today);//今日营业额
        Integer validOrderCount = reportMapper.countOrderByStatusAndDate(5,today);//今日有效订单数
        Integer orderCount = reportMapper.countOrderByStatusAndDate(5,today);//今日订单总数

        //订单完成率= 有效订单数/订单总数
        Double orderCompletionRate = 0.0;
        if (orderCount > 0 && validOrderCount > 0){
            orderCompletionRate = validOrderCount * 1.0 / orderCount;
            //保留4位小数
            orderCompletionRate = NumberUtil.round(orderCompletionRate,4).doubleValue();
        }
        //平均单价 = 营业额/有效订单数
        Double unitPrice = 0.0;
        if (validOrderCount > 0 && turnover > 0){
            unitPrice = turnover / validOrderCount;
            //保留两位小数
            unitPrice = NumberUtil.round(unitPrice,2).doubleValue();
        }

        //3. 组装返回结果
        BusinessDataVO businessDataVO = BusinessDataVO.builder()
                .newUsers(newUsers)//今日新增用户数
                .turnover(turnover)//今日营业额
                .validOrderCount(validOrderCount)//今日有效订单数
                .orderCompletionRate(orderCompletionRate)//订单完成率
                .unitPrice(unitPrice)//平均单价
                .build();

        return businessDataVO;
    }

    // 查询工作台  今日订单
    @Override
    public OrderOverViewVO overviewOrders() {
        //1. 获取今日日期
        LocalDate today = LocalDate.now();
        //2 查询SQL 凑数据  订单状态 1：待付款 2：待接单 3：(已接单)待派送 4：派送中 5：已完成 6：已取消 7：已退款
        Integer allOrders = reportMapper.countOrderByStatusAndDate(null,today);//今日订单总数

        Integer waitingOrders = reportMapper.countOrderByStatusAndDate(2,today);//待接单

        Integer deliveredOrders = reportMapper.countOrderByStatusAndDate(3,today); //待派送

        Integer completedOrders = reportMapper.countOrderByStatusAndDate(5,today);//已完成
        Integer cancelledOrders = reportMapper.countOrderByStatusAndDate(6,today);//已取消

        //3. 组装返回结果
        OrderOverViewVO orderOverViewVO = OrderOverViewVO.builder()
                .allOrders(allOrders)
                .waitingOrders(waitingOrders)
                .deliveredOrders(deliveredOrders)
                .completedOrders(completedOrders)
                .cancelledOrders(cancelledOrders)
                .build();

        return orderOverViewVO;
    }


    // 查询工作台  查询菜品总览
    @Override
    public DishOverViewVO overviewDishes() {
            String type = "dish";
            //查询已起售套餐数量
            Integer sold = reportMapper.getByIdAndStatus(StatusConstant.ENABLE,type);
            //查询停售套餐数量
            Integer discontinued = reportMapper.getByIdAndStatus(StatusConstant.DISABLE, type);
            return DishOverViewVO.builder()
                    .sold(sold)
                    .discontinued(discontinued)
                    .build();

        }


    // 查询工作台  查询套餐总览
    @Override
    public SetmealOverViewVO overviewSetmeals() {

            String type = "setmeal";//套餐
            Integer sold = reportMapper.getByIdAndStatus(StatusConstant.ENABLE, type);
            Integer discontinued = reportMapper.getByIdAndStatus(StatusConstant.DISABLE, type);
            return SetmealOverViewVO.builder()
                    .sold(sold)
                    .discontinued(discontinued)
                    .build();

    }


}



